package com.alibaba.scala.test1

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import scala.math.Ordering

object SortTest {
  
  object OrderContext{
    implicit val  girlOrdering = new Ordering[Girl1]{
      override def compare(x:Girl1,y:Girl1):Int={
        if(x.featureVal > y.featureVal) 1 
        else if(x.featureVal == y.featureVal){
           if(x.age > y.age) -1 else 1 
        }else
          -1 
      }
    }
  }
  
  
  def main(args: Array[String]): Unit = {
    val sconf = new SparkConf().setAppName("SortTest").setMaster("local[2]");
    sconf.set("spark.driver.memory", "471859200")
    val sc = new SparkContext(sconf)
    
    val rdd1 = sc.parallelize(List(("lihc",86,28,1),("anglebaba",86,24,3),("yuhailan",89,25,4)), 2)
    
    // 第一种方法用Ordered[T]
    val rdd2 = rdd1.sortBy(f=>Girl(f._2,f._3))

    // 第二种方式用 Orderding 
    // import OrderContext.girlOrdering
    // val rdd2 = rdd1.sortBy(f=>Girl1(f._2,f._3),false)
    
   println(rdd2.collect().toBuffer)
   
   sc.stop 
    
  }
  
  case class Girl1(val featureVal:Int,val age:Int) extends Serializable 
  
  case class Girl(val featureVal:Int,val age:Int) extends Ordered[Girl] with Serializable{
    
      override def compare(that:Girl):Int={
          if(this.featureVal == that.featureVal){
            that.age - this.age
          }else{
            this.featureVal - that.featureVal
          }
      }
  }
  
  
}